import React, { useState } from 'react';
import { Upload, message, Button, Modal } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { baseURL } from 'utils/request';
import { getToken } from 'utils/storage';

export default function TestPage() {
  const [imgUrl, setImgUrl] = useState('');
  const [fileList, setFileList] = useState([]);
  const props = {
    name: 'image',
    // 接受上传的文件类型
    accept: '.jpg,.jpeg,.png',
    action: `${baseURL}/v1_0/upload`,
    headers: {
      authorization: `Bearer ${getToken()}`,
    },
    onChange(info) {
      setFileList(info.fileList);
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 上传成功`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`);
      }
    },
    onPreview(file) {
      setImgUrl(file.thumbUrl);
    },
    beforeUpload(file) {
      console.log(file);
      // 设置白名单
      const typeWhite = ['image/jpg', 'image/jpeg', 'image/png'];
      if (!typeWhite.includes(file.type)) {
        message.warning('上传类型不对');
        return Upload.LIST_IGNORE;
      }
    },
  };
  return (
    <>
      <Upload {...props} listType="picture-card" fileList={fileList}>
        {/* 限制上传图片，超过规定张数，隐藏上传组件 */}
        {fileList.length < 3 && <Button icon={<PlusOutlined />}></Button>}
      </Upload>
      <Modal visible={!!imgUrl} footer={null} onCancel={() => setImgUrl('')}>
        <img style={{ width: '100%' }} src={imgUrl} alt="" />
      </Modal>
    </>
  );
}
